﻿using JFTest.CommunicationService;
using JFTest.Nlog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.WebControls.WebParts;

namespace JFTest.Communication
{
    public class ThreeDCam : TCPIPClentBase
    {
        private int _readTimeout = 3000;
        private TaskCompletionSource<string> _readResultTcs;
        public ThreeDCam()
        {
            InitializeClient();
            EndPoint endPoint = RemoteEndPoint;
            Name = "3D相机";            
        }
        public  async Task ConnectAsync(string host, int _port, int timeOut)
        {


            ip = host;
            port = _port;
            _readTimeout = timeOut;
            if (IsConnected) return;

            try
            {
                _cts = new CancellationTokenSource();
                await _tcpClient.ConnectAsync(host, port);
                _networkStream = _tcpClient.GetStream();
                OnConnectionStateChanged(true);
                StartReceiving();
                ColoredOutput.WriteStatusLine(PresetColor.Green, Name+"连接成功!!");     
                ColoredOutput.WriteOperationLine(PresetColor.Green, "开启"+ Name + "断联监控");
                StartReconnectMonitor();
            }
            catch (Exception ex)
            {
                OnErrorOccurred(ex);
                ColoredOutput.WriteStatusLine(PresetColor.Red, ex.Message);
               StartReconnectMonitor();
                
            }
        }

        /// <summary>
        /// 发送读码指令并等待结果
        /// </summary>
        /// <param name="command">读码指令</param>
        /// <returns>读码结果</returns>
        public async Task<string> SendReadCodeCommandAsync(string command)
        {
            
            if (!IsConnected)
                ColoredOutput.WriteStatusLine(PresetColor.Red,"未连接到"+Name);

            _readResultTcs = new TaskCompletionSource<string>();

            // 发送读码指令
            await SendStringAsync(command);

            // 等待结果或超时
            using (var cts = new CancellationTokenSource(_readTimeout))
            {
                try
                {
                    
                    cts.Token.Register(() => _readResultTcs.TrySetCanceled(), useSynchronizationContext: false);

                    return await _readResultTcs.Task;
                }
                catch (TaskCanceledException)
                {
                    ColoredOutput.WriteStatusLine(PresetColor.Red, "等待3D相机检测结果超时！");
                    
                    return "";

                }
            }
        }

        protected override void OnDataReceived(byte[] data)
        {
            base.OnDataReceived(data);

            // 将接收到的字节数据转换为字符串
            string result = Encoding.UTF8.GetString(data);

            // 如果 `_readResultTcs` 尚未完成，则设置结果
            if (_readResultTcs != null && !_readResultTcs.Task.IsCompleted)
            {
                _readResultTcs.TrySetResult(result);
            }
        }
    }
}
